#!/bin/bash

pwd

echo 相关构建信息
echo "是否备份当前版本：$1"
echo "版本：$2"
echo "是否灰度部署：$3"
echo "是否更新nginx-dictionary.conf文件：$4"
echo "是否重启nginx：$5"

# 获取参数
backup_flag=$1
version=$2
gray_flag=$3
updateSiteConfig=$4
nginxRestart=$5

echo 版本
yarn -v

echo 安装依赖
yarn install

echo 开始构建
yarn run build

if [ "$backup_flag" == "false" ]; then
    echo 备份旧版本
    backup_dir="/home/ubuntu/app/dictionary/backup-static/static-$version"
    mkdir -p $backup_dir
    cp -r /home/ubuntu/app/dictionary/static/* $backup_dir
fi

if [ "$gray_flag" == "true" ]; then
    echo 开始部署灰度环境
    static_gray_dir="/home/ubuntu/app/dictionary/static-gray"
    if [ ! -d "$static_gray_dir" ]; then
        mkdir -p $static_gray_dir
    fi
    rm -rf $static_gray_dir/*
    cp -r ./dist/* $static_gray_dir
else
    echo 开始部署生产环境
    static_dir="/home/ubuntu/app/dictionary/static"
    if [ ! -d "$static_dir" ]; then
        mkdir -p $static_dir
    fi
    rm -rf $static_dir/*
    cp -r ./dist/* $static_dir
fi

if [ "$updateSiteConfig" == "true" ]; then
    echo 更新nginx-dictionary.conf文件
    rm -f /etc/nginx/sites-enabled/nginx-dictionary.conf
    cp nginx-dictionary.conf /etc/nginx/sites-enabled/nginx-dictionary.conf
    cat /etc/nginx/sites-enabled/nginx-dictionary.conf
    nginx -t
fi

if [ "$nginxRestart" == "true" ]; then
    echo 重启nginx
    nginx -t
    nginx -s reload
fi

echo 部署完成
